/*
 * Flexigrid for jQuery -  v1.1
 *
 * Copyright (c) 2008 Paulo P. Marinas (code.google.com/p/flexigrid/)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 */
(function ($) {
	$.addFlex = function (t, p) {
		if (t.grid) return false; //return if already exist
		p = $.extend({ //apply default properties
			showSdiv: true, //是否显示sDiv
			searchitems:[{}],
			height: 'auto', //default height
			width: 'auto', //auto width
			striped: true, //apply odd even stripes
			novstripe: false,
			minwidth: 30, //min width of columns
			minheight: 80, //min height of columns
			resizable: false, //allow table resizing
			url: false, //URL if using data from AJAX
			method: 'POST', //data sending method
			dataType: 'json', //type of data for AJAX, either xml or json
			errormsg: 'Connection Error',
			usepager: false,
			nowrap: true,
			page: 1, //current page
			total: 1, //total pages
			useRp: true, //use the results per page select box
			rp: 30, //results per page
			rpOptions: [10,30,50,100], //allowed per-page values 
			title: false,
			pagestat: 'Displaying {from} to {to} of {total} items',
			pagetext: '当前页',
			outof: '总页数',
			findtext: 'Find',
			procmsg: '加载中, 请稍等 ...',
			query: '',
			qtype: '',
			nomsg: '无记录数',
			minColToggle: 1, //minimum allowed column to be hidden
			showToggleBtn: true, //show or hide column toggle popup
			hideOnSubmit: true,
			autoload: true,
			blockOpacity: 0.5,
			preProcess: false,
			onDragCol: false,
			onToggleCol: false,
			onChangeSort: false,
			onSuccess: false,
			onError: function(XMLHttpRequest, textStatus, errorThrown){
				$("#dialog-message").html(XMLHttpRequest.responseText);
				$( "#dialog-message" ).dialog({
					modal: true,
					width:1000,
					height:650,
					buttons: {
						Ok: function() {
							$( this ).dialog( "close" );
						}
					}
				});
			},
			/*查询前的调用函数，函数定义function(grid,t,p) 
			* grid 包含列表的div对象 
			* t grid的显示table对象（jquey）p 封装全局参数
			* 返回boolean类型，返回fasle中断查询，返回true执行查询
			*/
			onSubmit: false, 
			showchecked:false,//是否显示复选框
			columnhide:false,
			onselect:false,//tr选中事件，参数类型(主键标识,显示信息showAction)
			searchDiv:'',
			singleSelect:true,//是否单行显示
			showHideCol:false,//是否可以选择列的显示和隐藏
			searchCall:false,//查询后的回调函数,函数定义function(data);data为服务器端的返回
			cacheDefProps:false, //查询后的条件缓存处理，格式：[{id: '控件id值', name: '控件name值', colName: '后台列的属性名称'}]
			useBtn:true, //是否显示按钮工具栏
			useSearch:true, //是否显示搜索层
			mixValHid:false, //整合id值的隐藏域控件的id
			cbxClick: false, //数据行id复选框的选中事件
			singleCheck:false, //是否只允许选择一个
			infoFlex: false, //{name:'隐藏域名称',tips:'复选框没选中的提示信息',required:true//是否必选,before:function(){}//前置验证行为}
			checkAll: true
		}, p, {pagestat: '{from}到{to}，总数{total}条'});
		//$(t).empty();
		$(t).show() //show if hidden
			.attr({
				cellPadding: 0,
				cellSpacing: 0,
				border: 0
			}) //remove padding and spacing
			.removeAttr('width'); //remove width properties
		//create grid class
		var g = {
			serachHeight:0,
			hset: {},
			rePosDrag: function () {
				var cdleft = 0 - this.hDiv.scrollLeft;
				if (this.hDiv.scrollLeft > 0) cdleft -= Math.floor(p.cgwidth / 2);
				$(g.cDrag).css({
					top: g.hDiv.offsetTop + 1
				});
				var cdpad = this.cdpad;
				$('div', g.cDrag).hide();
				$('thead tr:first th:visible', this.hDiv).each(function () {
					var n = $('thead tr:first th:visible', g.hDiv).index(this);
					var cdpos = parseInt($('div', this).width());
					if (cdleft == 0) cdleft -= Math.floor(p.cgwidth / 2);
					cdpos = cdpos + cdleft + cdpad;
					if (isNaN(cdpos)) {
						cdpos = 0;
					}
					$('div:eq(' + n + ')', g.cDrag).css({
						'left': cdpos + 'px'
					}).show();
					cdleft = cdpos;
				});
			},
			fixHeight: function (newH) {
				newH = false;
				if (!newH) newH = $(g.bDiv).height();
				var hdHeight = $(this.hDiv).height();
				$('div', this.cDrag).each(
					function () {
						$(this).height(newH + hdHeight);
					}
				);
				var nd = parseInt($(g.nDiv).height());
				if (nd > newH) $(g.nDiv).height(newH).width(200);
				else $(g.nDiv).height('auto').width('auto');
				$(g.block).css({
					height: newH,
					marginBottom: (newH * -1)
				});
				var hrH = g.bDiv.offsetTop + newH;
				if (p.height != 'auto' && p.resizable) hrH = g.vDiv.offsetTop;
				$(g.rDiv).css({
					height: hrH
				});
			},
			setbdivheight:function (){
				//var tabs = $('#tabs');
				var tabs = $(".ui-layout-center");
				//tabs容器的高度
				var tabsht = tabs.outerHeight(true);
				//alert(tabsht);
				//导航高度
				var tabNavht = $('ul',tabs).outerHeight(true);
				//查询div的高度
				var sht = $(g.sDiv).outerHeight(true);
				//title container高度
				var containerht = $(g.mDiv).outerHeight(true);
				//toolbar 高度 
				var toolbarht =  $(g.tDiv).outerHeight(true);
				//表头高度
				var headht = $(g.hDiv).outerHeight(true);
				//分页页面的高度
				var pageht = $(g.pDiv).outerHeight(true);
				g.serachHeight = sht;
				//alert("tabsht:"+tabsht+" tabNavht:"+tabNavht+" sht:"+sht+" containerht:"+containerht+" toolbarht:"+toolbarht+" headht:"+headht+"pageht:"+pageht);
				var bht = tabsht-tabNavht-sht-containerht-toolbarht-headht-pageht -3;
				//alert(bht);
				if(p.height != 'auto'){
					bht=p.height;
				}
				if(bht<0){
					bht=300;
				}
				return $(g.bDiv).css({
					height: bht+"px"
				});
			},
			dragStart: function (dragtype, e, obj) { //default drag function start
				if (dragtype == 'colresize') {//column resize
					$(g.nDiv).hide();
					$(g.nBtn).hide();
					var n = $('div', this.cDrag).index(obj);
					var ow = $('th:visible div:eq(' + n + ')', this.hDiv).width();
					$(obj).addClass('dragging').siblings().hide();
					$(obj).prev().addClass('dragging').show();
					this.colresize = {
						startX: e.pageX,
						ol: parseInt(obj.style.left),
						ow: ow,
						n: n
					};
					$('body').css('cursor', 'col-resize');
				} else if (dragtype == 'vresize') {//table resize
					var hgo = false;
					$('body').css('cursor', 'row-resize');
					if (obj) {
						hgo = true;
						$('body').css('cursor', 'col-resize');
					}
					this.vresize = {
						h: p.height,
						sy: e.pageY,
						w: p.width,
						sx: e.pageX,
						hgo: hgo
					};
				} else if (dragtype == 'colMove') {//column header drag
					$(g.nDiv).hide();
					$(g.nBtn).hide();
					this.hset = $(this.hDiv).offset();
					this.hset.right = this.hset.left + $('table', this.hDiv).width();
					this.hset.bottom = this.hset.top + $('table', this.hDiv).height();
					this.dcol = obj;
					this.dcoln = $('th', this.hDiv).index(obj);
					this.colCopy = document.createElement("div");
					this.colCopy.className = "colCopy";
					this.colCopy.innerHTML = obj.innerHTML;
					if ($.browser.msie) {
						this.colCopy.className = "colCopy ie";
					}
					$(this.colCopy).css({
						position: 'absolute',
						float: 'left',
						display: 'none',
						textAlign: obj.align
					});
					$('body').append(this.colCopy);
					$(this.cDrag).hide();
				}
				$('body').noSelect();
			},
			getValue:function ($entity,$property){
				var propertyValue ="";
				if($entity!=null){
					var property = $property.split(".");
					$.each(property,function(i,n){
						if($entity[n]||$entity[n]==0){
							propertyValue =$entity[n];
							$entity = propertyValue;
						}else{
							propertyValue="";
							return false;
						}
					});
//					if(propertyValue!=0){
//						propertyValue = propertyValue||'';
//					}
				}
				if(typeof(propertyValue)=='string'){
					//字符去前后空格处理
					propertyValue = $.trim(propertyValue);
				}
				return propertyValue;
			},
			getColumnModel: function(cmName,cm) {
				for(var val in cm){
					val = cm[val];
					if(cmName==val.name) {
						return val;
					} else {
						if(val.sortName) {
							if(cmName == val.sortName){
								return val;
							}
						}
					}
				}
			},
			dragMove: function (e) {
				if (this.colresize) {//column resize
					var n = this.colresize.n;
					var diff = e.pageX - this.colresize.startX;
					var nleft = this.colresize.ol + diff;
					var nw = this.colresize.ow + diff;
					if (nw > p.minwidth) {
						$('div:eq(' + n + ')', this.cDrag).css('left', nleft);
						this.colresize.nw = nw;
					}
				} else if (this.vresize) {//table resize
					var v = this.vresize;
					var y = e.pageY;
					var diff = y - v.sy;
					if (!p.defwidth) p.defwidth = p.width;
					if (p.width != 'auto' && !p.nohresize && v.hgo) {
						var x = e.pageX;
						var xdiff = x - v.sx;
						var newW = v.w + xdiff;
						if (newW > p.defwidth) {
							this.gDiv.style.width = newW + 'px';
							p.width = newW;
						}
					}
					var newH = v.h + diff;
					if ((newH > p.minheight || p.height < p.minheight) && !v.hgo) {
						this.bDiv.style.height = newH + 'px';
						p.height = newH;
						this.fixHeight(newH);
					}
					v = null;
				} else if (this.colCopy) {
					$(this.dcol).addClass('thMove').removeClass('thOver');
					if (e.pageX > this.hset.right || e.pageX < this.hset.left || e.pageY > this.hset.bottom || e.pageY < this.hset.top) {
						//this.dragEnd();
						$('body').css('cursor', 'move');
					} else {
						$('body').css('cursor', 'pointer');
					}
					$(this.colCopy).css({
						top: e.pageY + 10,
						left: e.pageX + 20,
						display: 'block'
					});
				}
			},
			dragEnd: function () {
				if (this.colresize) {
					//alert('dragEnd');
					var n = this.colresize.n;
					var nw = this.colresize.nw;
					$('th:visible div:eq(' + n + ')', this.hDiv).css('width', nw);
					$('tr', this.bDiv).each(
						function () {
							$('td:visible div:eq(' + n + ')', this).css('width', nw);
						}
					);
					var abbr = $('th:visible:eq(' + n + ')', this.hDiv).attr('abbr');
					$('input[name="'+(p.cookieId+'.'+abbr)+'"]',this.nDiv).attr('colWidth',nw);
					this.hDiv.scrollLeft = this.bDiv.scrollLeft;
					$('div:eq(' + n + ')', this.cDrag).siblings().show();
					$('.dragging', this.cDrag).removeClass('dragging');
					this.rePosDrag();
					this.fixHeight();
					this.colresize = false;
					var cbAry = $('input', g.nDiv);
					var ary = [];
					$.each(cbAry, function(i, val) {
				      ary.push($(val).attr('name') + '=' + ($(val).attr('checked')=='checked')+'|width='+$(val).attr('colWidth'));
				    });
					$.cookie(p.cookieId+'ary',ary.toString(),{expires:20*365});
					//alert('设置个性化定义');
				} else if (this.vresize) {
					this.vresize = false;
				} else if (this.colCopy) {
					$(this.colCopy).remove();
					if (this.dcolt != null) {
						if (this.dcoln > this.dcolt) $('th:eq(' + this.dcolt + ')', this.hDiv).before(this.dcol);
						else $('th:eq(' + this.dcolt + ')', this.hDiv).after(this.dcol);
						this.switchCol(this.dcoln, this.dcolt);
						$(this.cdropleft).remove();
						$(this.cdropright).remove();
						this.rePosDrag();
						if (p.onDragCol) {
							p.onDragCol(this.dcoln, this.dcolt);
						}
					}
					this.dcol = null;
					this.hset = null;
					this.dcoln = null;
					this.dcolt = null;
					this.colCopy = null;
					$('.thMove', this.hDiv).removeClass('thMove');
					$(this.cDrag).show();
				}
				$('body').css('cursor', 'default');
				$('body').noSelect(false);
			},
			toggleCol: function (cid, visible) {
				var ncol = $("th[axis='col" + cid + "']", this.hDiv)[0];
				var n = $('thead th', g.hDiv).index(ncol);
				var cb = $('input[value=' + cid + ']', g.nDiv)[0];
				if (visible == null) {
					visible = ncol.hidden;
				}
				if ($('input:checked', g.nDiv).length < p.minColToggle && !visible) {
					return false;
				}
				if (visible) {
					ncol.hidden = false;
					$(ncol).show();
					cb.checked = true;
				} else {
					ncol.hidden = true;
					$(ncol).hide();
					cb.checked = false;
				}
				$('tbody tr', t).each(
					function () {
						if (visible) {
							$('td:eq(' + n + ')', this).show();
						} else {
							$('td:eq(' + n + ')', this).hide();
						}
					}
				);
				this.rePosDrag();
				if (p.onToggleCol) {
					p.onToggleCol(cid, visible);
				}
				return visible;
			},
			switchCol: function (cdrag, cdrop) { //switch columns
				
				$('tbody tr', t).each(
					function () {
						if (cdrag > cdrop) $('td:eq(' + cdrop + ')', this).before($('td:eq(' + cdrag + ')', this));
						else $('td:eq(' + cdrop + ')', this).after($('td:eq(' + cdrag + ')', this));
					}
				);
				//switch order in nDiv
				cdrag = cdrag-1;
				cdrop = cdrop-1;
				if (cdrag > cdrop) {
					
					$('tr:eq(' + cdrop + ')', this.nDiv).before($('tr:eq(' + cdrag + ')', this.nDiv));
				} else {
					
					$('tr:eq(' + cdrop + ')', this.nDiv).after($('tr:eq(' + cdrag + ')', this.nDiv));
				}
				if ($.browser.msie && $.browser.version < 7.0) {
					$('tr:eq(' + cdrop + ') input', this.nDiv)[0].checked = true;
				}
				this.hDiv.scrollLeft = this.bDiv.scrollLeft;
				//save setting to cookie
				var cbAry = $('input', g.nDiv);
				var ary = [];
				$.each(cbAry, function(i, val) {
			      ary.push($(val).attr('name') + '=' + ($(val).attr('checked')=='checked')+'|width='+$(val).attr('colWidth'));
			    });
				//alert(ary.toString());
				$.cookie(p.cookieId+'ary',ary.toString(),{expires:20*365});
			},
			scroll: function () {
				this.hDiv.scrollLeft = this.bDiv.scrollLeft;
				//this.rePosDrag();
			},
			cookieSet:function(){
				var cmCopy = [];
				if(p.cookieId){
					var setting = $.cookie(p.cookieId+'ary');
					if(setting){
						//alert('获取到个性化设置');
						setting = setting.split(',');
						$.each(setting,function(i,val){
							var configs = val.split('|');
							var showConfig = configs[0].split('=');
							var cm = g.getColumnModel(showConfig[0].replace(p.cookieId+'.',''), p.colModel);
							if(cm!=undefined){
								cm.hide = (showConfig[1]=='false');
								if(configs[1]) {
									var widthConfig = configs[1].split('=');
									if(widthConfig[0]&& widthConfig[1]) {
										cm.width = widthConfig[1];
									}else{
										if(!cm.width){
											cm.width=100;
										}
									}
								}
								cmCopy.push(cm);
							}
						});
					}
				}
				if(cmCopy && cmCopy.length > 0) {
					if(p.colModel.length > cmCopy.length) {
						for(var i=p.colModel.length-(p.colModel.length-cmCopy.length)-1,j=p.colModel.length;i<j;i++) {
							cmCopy.push(p.colModel[i]);
						}
					}
					p.colModel = cmCopy;
				}
			},
			addData: function (data) { //parse data
				var begin = new Date();
				if (p.dataType == 'json') {		
					data = $.extend({rows: [], page: 0, total: 0}, data);
					if(!p.usepager)
						data.total = 1;
				}
				if (p.preProcess) {
					data = p.preProcess(data);
				}
				$('.pReload', this.pDiv).removeClass('loading');
				this.loading = false;
				if (!data) {
					$('.pPageStat', this.pDiv).html(p.errormsg);
					return false;
				}
				p.total = data.total; //总行数
				//如果是分页查询，总行数为零，或者不分页查询，结果集行数为零，清空控件并解绑事件
				if (p.usepager && p.total == 0 || data.rows.length == 0) {
					$('tr, a, td, div', t).unbind();
					$(t).empty();
					p.pages = 1;
					p.page = 1;
					this.buildpager();
					$('.pPageStat', this.pDiv).html(p.nomsg);
					return false;
				}
				p.pages = Math.ceil(p.total / p.rp);
				p.page = data.page;
				this.buildpager();
				$('tr', t).unbind();
				$(t).empty();
				//build new body 把原有的dom方式修改为字符串封装方式一次性填充div
				var tbHtml =[]; 
				tbHtml.push("<tbody>");
				var ths = $('thead tr:first th', g.hDiv);
                //var thsdivs = $('thead tr:first th div', g.hDiv);
				if (p.dataType == 'json') {
					//======================================
					g.cookieSet();
					
					var targetRows = []; //目标数据行
					//设置了cbx整合id拼接字符串或内嵌flex的情况，生成数据行时，复选框选中的在前，不选中的在后
					if(p.mixValHid || p.infoFlex) {
						var checkedRows = []; //复选框需要选中的数据行
						var notCheckedRows= []; //复选框不需要选中的数据行
						var mixId = $(".detail " + p.mixValHid).val(); //获取用户的cbx整合id拼接字符串
						var idArr = [];
						if(mixId) {
							idArr = mixId.split(",");
						}
						var checkedCbxes;
						if(p.infoFlex) {
							//获取内嵌flex缓存中所保存的选中的复选框对象
							checkedCbxes = $(t).data("checked");
							//如果缓存中不存在，证明是第一次加载，生成缓存对象
							if(!checkedCbxes) {
								checkedCbxes = {};
								$(".detail #infoForm .hidMix").each(function(){
									//如果页面的id隐藏域的name值与配置中的匹配，把id隐藏域保存到缓存对象中（key：隐藏域的值，val：隐藏域对象）
									if($(this).attr("name") === p.infoFlex.name) {
										checkedCbxes[$(this).val()] = $(this);
									}
								});
								$(t).data("checked", checkedCbxes);
							}
						}
						$.each(data.rows, function(i, row){
							var rowId = row.id.toString();
							//如果数据行的id在选中范围内，添加到选中列表中
							if($.inArray(rowId, idArr) !== -1 || (checkedCbxes !== undefined && checkedCbxes[rowId])) {
								row['checked'] = true; //标识复选框需要选中
								checkedRows.push(row); //保存复选框需要选中的数据行
							} else {
								notCheckedRows.push(row); //保存复选框不需要选中的数据行
							}
						});
						/*数据行排序，复选框选中的在前，不选中的在后*/
						//先生成复选框需要选中的数据行
						$.each(checkedRows, function(i, row){
							targetRows.push(row); 
						});
						//后生成复选框不需要选中的数据行
						$.each(notCheckedRows, function(i, row){
							targetRows.push(row);
						});
					} else {
					//没有设置了cbx整合id拼接字符串的情况，直接获取原数据行
						targetRows = data.rows;
					}
					
					//生成表格数据
					$.each(targetRows, function (i, row) {
						var rowId = row.id;
						tbHtml.push("<tr id='","row",rowId,"'");
						//TODO 添加表行onclick事件
						if(p.onselect){
							tbHtml.push(" dblclick = g.dblclickfn('",rowId,"')");
						}
						if (i % 2 && p.striped) {
							tbHtml.push(" class='erow'");
						}
						tbHtml.push(">");
						ths.each( //add cell
							function () {
								tbHtml.push("<td align='",this.align,"'"," abbr='",$(this).attr('abbr'),"'");
								
								var idx = $(this).attr('axis').substr(3);
								//TODO 添加复选框
								if(p.showchecked&&idx==0){
									tbHtml.push(">");
									//复选框选中设置
									var checkedHtml = "";
									if(row.checked) {
										checkedHtml = 'checked="checked"';
									}
									
									tbHtml.push('<div style="width:30px"><input name="ids" type="checkbox" '+checkedHtml+' value="'+rowId+'"/></div>');
								}else{
									if(p.showchecked){idx = idx-1;}
									var col = p.colModel[idx];
									if(!col.textAlign) {
										col.textAlign = 'center';
									}
									var showcol = '';
									//alert(col.name+' '+col.hide);
									if(col.hide){
										showcol = 'none';
									}
									var propVal = g.getValue(row,col.name);
									tbHtml.push("style='display:",showcol,"'>");
									tbHtml.push('<div style="width:',col.width,'px;','text-align:',col.textAlign,';"');
									//添加提示信息
									if(col.isTitle) {
										tbHtml.push(" title='", propVal, "'");
									}
									tbHtml.push('>', propVal);
									tbHtml.push('</div>');
								}
								tbHtml.push("</td>");
							}
						);
						tbHtml.push("</tr>");
					});
				}
				tbHtml.push("</tbody>");
				//alert(tbHtml.join(""));
				$(t).append(tbHtml.join(""));
				//单选、复选框点击事件、内嵌flex
				if(p.singleCheck || p.cbxClick || p.infoFlex) {
					$(":checkbox[name='ids']", t).click(function(){
						var $cbx = $(this);
						//如果设置了单选，其它选中项取消选中（排除自身）
						if(p.singleCheck) {
							$(":checkbox[name='ids']:checked", t).not($cbx).prop("checked", false);
						}
						//添加复选框的点击事件
						if(p.cbxClick) {
							p.cbxClick($(g.gDiv), $(t), $cbx);
						}
						//内嵌flex，复选框选中或反选时保存复选框对象到缓存中
						if(p.infoFlex) {
							var checkedCbxes = $(t).data("checked");
							//如果还没有生成缓存数据或者是单选的情况，重新生成缓存数据
							if(!checkedCbxes || p.singleCheck) {
								checkedCbxes = {};
								$(t).data("checked", checkedCbxes);
							}
							var cbxId = $cbx.val(); //复选框id
							//复选框选中，将复选框对象添加到缓存中（key为复选框id）
							if($cbx.prop("checked")) {
								checkedCbxes[cbxId] = $cbx;
							} else {
							//复选框反选，从缓存中移除复选框对象（key为复选框id）
								delete checkedCbxes[cbxId];
							}
						}
					});
					if(p.infoFlex) {
						//如果指定了内嵌flex的情况，全选的话将所有的复选框对象添加到缓存中，反选的话从缓存中清除所有的复选框对象
						$(".cbxAll", this.hDiv).click(function(){
							var checkedCbxes = $(t).data("checked");
							if($(this).prop("checked")) {
								$(":checkbox[name='ids']", t).each(function(){
									var $cbx = $(this); 
									checkedCbxes[$cbx.val()] = $cbx;
								});
							} else {
								$(t).data("checked", {});
							}
						});
					}
				}
				//this.addCellProp();//添加列属性
				
				this.addRowProp();//添加行属性
				var end = (new Date() - begin)/1000;
				//alert(end+"秒");
				//this.rePosDrag();
				
				tbHtml = null;
				data = null;
				i = null;
				if (p.onSuccess) {
					p.onSuccess(this);
				}
				if (p.hideOnSubmit) {
					$(g.block).remove();
				}
				this.hDiv.scrollLeft = this.bDiv.scrollLeft;
				if ($.browser.opera) {
					$(t).css('visibility', 'visible');
				}
			},
			//信息窗内嵌Flex处理
			opInfoFlex: function() {
				var $infoForm = $(".detail #infoForm");
				
				//infoForm缓存内嵌flex的属性对象（以内嵌flex的table的id为key）
				var totalInfoFlex = $infoForm.data("totalInfoFlex");
				if(!totalInfoFlex) {
					totalInfoFlex = {};
					$infoForm.data("totalInfoFlex", totalInfoFlex);
				}
				totalInfoFlex[$(t).attr("id")] = p.infoFlex;
				//如果已经绑定到最后一个内嵌flex，先判断infoForm有没有绑定过事件，如果没有绑定过，进行submit事件的绑定
				if($(".detail .flexigrid").index($(t).parents(".flexigrid")) === $(".detail .flexigrid").length - 1 && !$infoForm.data("bindSubmit")) {
					$infoForm.submit(function(){
						var isPass = true; //表单提交是否通过，默认为允许
						var hidMixIdHtmls = []; //整合id的隐藏域列表
						//遍历每一个内嵌flex，获取其属性对象和已选择的复选框
						$(".detail .flexigrid .bDiv table").each(function(){
							var $flexTbl = $(this);
							var infoFlex = totalInfoFlex[$flexTbl.attr("id")]; //从缓存中获取内嵌flex的属性对象
							//前置处理（如果返回false，跳出内嵌flex的遍历，提示错误信息，不进行表单的提交）
							if(infoFlex.before) {
								isPass = infoFlex.before($infoForm, $flexTbl, $flexTbl.parents(".flexigrid"));
								if(!isPass) {
									return isPass;
								}
							}
							var cbxChoose = $flexTbl.data("checked");
							if($.isEmptyObject(cbxChoose)) {
								$(".hidMix[name=" + infoFlex.name + "]").remove(); //如果没有选中任何复选框，与其关联的隐藏域需要被清空
								//设置了复选框为必选的情况，进行选中的验证，如果没有选中，跳出内嵌flex的遍历，提示错误信息，不进行表单的提交
								if(infoFlex.required) {
									hiAlert(infoFlex.tips, "提示");
									isPass = false;
									return isPass;
								}
							} else {
								//如果选中了，进行隐藏域的生成
								$.each(cbxChoose, function(k, cbx){
									hidMixIdHtmls.push("<input class='hidMix' type='hidden' name='" + infoFlex.name + "' value='" + cbx.val() + "' />");
								});
							}
						});
						if(hidMixIdHtmls.length > 0) {
							$(".hidMix", this).remove(); //先清空之前保存的id隐藏域列表
							$(this).prepend(hidMixIdHtmls.join("")); //添加新保存的id隐藏域列表
						}
						return isPass;
					});
					$infoForm.data("bindSubmit", 1); //在缓存中标识infoForm已经绑定了submit事件
				}
			},
			changeSort: function (th) { //change sortorder
				if (this.loading) {
					return true;
				}
				$(g.nDiv).hide();
				$(g.nBtn).hide();
				
				/*if (p.sortname == $(th).attr('abbr')) {
					if (p.sortorder == 'asc') {
						p.sortorder = 'desc';
					} else {
						p.sortorder = 'asc';
					}
				}
				$(th).addClass('sorted').siblings().removeClass('sorted');
				$('.sdesc', this.hDiv).removeClass('sdesc');
				$('.sasc', this.hDiv).removeClass('sasc');
				$('div', th).prop("class", 's' + p.sortorder);
				p.sortname = $(th).attr('abbr');*/
				
				if(p.sortname && p.sortorder) {
					var sortnames = p.sortname.split(","); //排序属性集
					var sortorders = p.sortorder.split(","); //排序规则集
					var currPropName = $(th).attr('abbr'); //获取当前属性
					var sortIndex = $.inArray(currPropName, sortnames);
					var currPropOrder = "";
					//如果当前属性在排序属性集中，获取反向的排序规则
					if(sortIndex !== -1) {
						currPropOrder = sortorders[sortIndex] === "asc" ? "desc" : "asc";
					} else {
					//如果当前属性不在排序属性集中，获取排序属性集中第一个属性的排序规则
						currPropOrder = sortorders[0];
					}
					//原样式清除
					$(th).addClass('sorted').siblings().removeClass('sorted');
					$('.sdesc', this.hDiv).removeClass('sdesc');
					$('.sasc', this.hDiv).removeClass('sasc');
					//设置新的排序规则给当前属性
					$('div', th).prop("class", 's' + currPropOrder);
					p.sortname = $(th).attr('abbr'); //保存新的排序属性
					p.sortorder = currPropOrder; //保存新的排序规则
				}
				
				if (p.onChangeSort) {
					p.onChangeSort(p.sortname, p.sortorder);
				} else {
					this.populate();
				}
			},
			buildpager: function () { //rebuild pager based on new properties
				$('.pcontrol input', this.pDiv).val(p.page);
				$('.pcontrol span', this.pDiv).html(p.pages);
				var r1 = (p.page - 1) * p.rp + 1;
				var r2 = r1 + p.rp - 1;
				if (p.total < r2) {
					r2 = p.total;
				}
				var stat = p.pagestat;
				stat = stat.replace(/{from}/, r1);
				stat = stat.replace(/{to}/, r2);
				stat = stat.replace(/{total}/, p.total);
				$('.pPageStat', this.pDiv).html(stat);
			},
			populate: function () { //get latest data
				if (this.loading) {
					return true;
				}
				//不需要显示sDiv的情况下，把搜索层的内容拷贝到sDiv中
				if(p.searchDiv != '' && !p.showSdiv) {
					copySearchDivContent($(p.searchDiv), $(g.sDiv), false);
				}
				if (p.onSubmit) {
					var gh = p.onSubmit(g.gDiv,$(t),p);
					if (!gh) {
						return false;
					}
				}
				this.loading = true;
				if (!p.url) {
					return false;
				}
				$('.pPageStat', this.pDiv).first().html(p.procmsg);
				$('.pReload', this.pDiv).addClass('loading');
				$(g.block).css({
					top: g.bDiv.offsetTop
				});
				if (p.hideOnSubmit) {
					$(this.gDiv).prepend(g.block);
				}
				if ($.browser.opera) {
					$(t).css('visibility', 'hidden');
				}
				if (!p.newp) {
					p.newp = 1;
				}
				if (p.page > p.pages) {
					p.page = p.pages;
				}
				var param = [{
					name: 'pager.currentPage',
					value: p.newp
				}, {
					name: 'pager.pageSize',
					value: p.rp
				}, {
					name: 'sortname',
					value: p.sortname
				}, {
					name: 'sortorder',
					value: p.sortorder
				}, {
					name: 'query',
					value: p.query
				}, {
					name: 'qtype',
					value: p.qtype
				}
				];
	//			alert(p.qtype);
	//			alert(p.query);
	//			alert(p.params);
				if (p.params) {
					for (var pi = 0; pi < p.params.length; pi++) {
						param[param.length] = p.params[pi];
					}
				}
				//TODO 查询条件封装
				if(p.searchDiv!=''){
					var queryParam = $('.searchForm', g.gDiv).serializeArray();
					for (var pi = 0; pi < queryParam.length; pi++) {
						param[param.length] = queryParam[pi];
					}
					//不需要显示sDiv的情况，清空日期控件的id和hasDatepicker的类，防止再次选择日期时失效
					if(!p.showSdiv) {
						$(".time", p.searchDiv).removeAttr("id").removeClass("hasDatepicker");
					}
				}
				param[param.length] = {name:p.qtype,value:p.query};
				var beginTime = new Date();
				$.ajax({
					type: p.method,
					url: p.url,
					data: param,
					dataType: p.dataType,
					success: function (data) {
						//var addDateTime = new Date() - beginTime;
						g.addData(data);
						//查询后，如果搜索层为全部显示状态，进行局部显示(还原搜索层)
						//如果显示了sDiv，还原sDiv下的搜索层，否则还原searchDiv下的搜索层
						var sepDiv = $("div.sepShow", p.showSdiv ? g.sDiv : p.searchDiv);
						if(sepDiv.length > 0) {
							opSearchDivDisplay(sepDiv); //隐藏搜索浮动层
						}
						//查询后的处理
						if(p.searchCall){
							p.searchCall(data, $(t), g.gDiv);
						}
						//信息窗内嵌Flex处理
						if(p.infoFlex) {
							g.opInfoFlex();
						}
						//绑定HTML内容弹出框
						$("a[name='demo-basic']", g.gDiv).poshytip();
						//如果有绑定tr的点击事件，查询完成后，默认使第一条记录选中
						if(p.onclick) {
							var tblTrs = $("tr", t);
							if(tblTrs.length > 0) {
								tblTrs.eq(0).click();
							}
						}
//						//如果左边导航栏打开了，隐藏左边导航栏
//						if($(".ui-layout-resizer-west span.content-open").css("display") === 'block') {
//							$(".ui-layout-resizer-west span.content-open").click();
//						}
						//添加执行时间
						var endTime = new Date();
						var executeTime = endTime - beginTime;
						//alert(executeTime);
						$('.executeTime', g.pDiv).html("耗时"+executeTime/1000+"秒");
						
						//如果需要进行查询后的缓存处理，进行相应列的值设置
						if(p.cacheDefProps && p.cacheDefProps.length > 0) {
							var targetSearchDiv = p.showSdiv ? g.sDiv : p.searchDiv; //获取目标搜索层
							$.each(p.cacheDefProps, function(i, cacheDefProp){
								var eleId = cacheDefProp.id; //缓存隐藏域的id
								var eleVal = eval("data." + cacheDefProp.colName); //获取所定义的列，在列表查询后的值
								if($(eleId, targetSearchDiv).length === 0) {
									//如果该列对应的隐藏域并未生成，在searchForm下生成隐藏域，并进行id(去除井号)、name属性的设置和赋值
									$(".searchForm", targetSearchDiv).append(
										$("<input type='hidden' id='" + eleId.substring(1) + "' name='" + cacheDefProp.name + "' value='" + eleVal + "' />")
									);
								} else {
									//如果该列对应的隐藏域已经生成，直接进行赋值
									$(eleId, targetSearchDiv).val(eleVal);
								}
							});
						}
					},
					error: function (XMLHttpRequest, textStatus, errorThrown) {
						try {
							if (p.onError) p.onError(XMLHttpRequest, textStatus, errorThrown);
						} catch (e) {
							
						}
					}
				});
				
			},
			doSearch: function () {
				//p.query = $('input[name=q]', g.sDiv).val();
				//p.qtype = $('select[name=qtype]', g.sDiv).val();
				//p.newp = 1;
				//alert(p.query);
				this.populate();
				
			},
			changePage: function (ctype) { //change page
				if (this.loading) {
					return true;
				}
				switch (ctype) {
					case 'first':
						p.newp = 1;
						break;
					case 'prev':
						if (p.page > 1) {
							p.newp = parseInt(p.page) - 1;
						}
						break;
					case 'next':
						if (p.page < p.pages) {
							p.newp = parseInt(p.page) + 1;
						}
						break;
					case 'last':
						p.newp = p.pages;
						break;
					case 'input':
						var nv = parseInt($('.pcontrol input', this.pDiv).val());
						if (isNaN(nv)) {
							nv = 1;
						}
						if (nv < 1) {
							nv = 1;
						} else if (nv > p.pages) {
							nv = p.pages;
						}
						$('.pcontrol input', this.pDiv).val(nv);
						p.newp = nv;
						break;
				}
				if (p.newp == p.page) {
					return false;
				}
				if (p.onChangePage) {
					p.onChangePage(p.newp);
				} else {
					this.populate();
				}
			},
			addCellProp: function () {
				$('tbody tr td', g.bDiv).each(function () {
					var tdDiv = document.createElement('div');
					var n = $('td', $(this).parent()).index(this);
					var pth = $('th:eq(' + n + ')', g.hDiv).get(0);
					if (pth != null) {
						if (p.sortname&&p.sortname == $(pth).attr('abbr')) {
							this.className = 'sorted';
						}
						$(tdDiv).css({
							textAlign: pth.align,
							width: $('div:first', pth)[0].style.width
						});
						if (pth.hidden) {
							$(this).css('display', 'none');
						}
					}
					if (p.nowrap == false) {
						$(tdDiv).css('white-space', 'normal');
					}
					if (this.innerHTML == '') {
						this.innerHTML = '&nbsp;';
					}
					tdDiv.innerHTML = this.innerHTML;
					var prnt = $(this).parent()[0];
					var pid = false;
					if (prnt.id) {
						pid = prnt.id.substr(3);
					}
					if (pth != null) {
						if (pth.process) pth.process(tdDiv, pid);
					}
					$(this).empty().append(tdDiv).removeAttr('width'); //wrap content
				});
			},
			getCellDim: function (obj) {// get cell prop for editable event
				var ht = parseInt($(obj).height());
				var pht = parseInt($(obj).parent().height());
				var wt = parseInt(obj.style.width);
				var pwt = parseInt($(obj).parent().width());
				var top = obj.offsetParent.offsetTop;
				var left = obj.offsetParent.offsetLeft;
				var pdl = parseInt($(obj).css('paddingLeft'));
				var pdt = parseInt($(obj).css('paddingTop'));
				return {
					ht: ht,
					wt: wt,
					top: top,
					left: left,
					pdl: pdl,
					pdt: pdt,
					pht: pht,
					pwt: pwt
				};
			},
			addRowProp: function () {
				$('tbody tr', g.bDiv).each(function () {
					$(this).click(function (e) {
						var obj = (e.target || e.srcElement);
						if (obj.href || obj.type) return true;
						$(this).toggleClass('trSelected');
						if (p.singleSelect) $(this).siblings().removeClass('trSelected');
						p.selectId = $(this).attr("id").substr(3);
						if(p.onclick){
							p.onclick.call("click",g.gDiv,$(t),p,p.onclick.params);
						}
						p.selectId=false;
					}).mousedown(function (e) {
						if (e.shiftKey) {
							$(this).toggleClass('trSelected');
							g.multisel = true;
							this.focus();
							$(g.gDiv).noSelect();
						}
					}).mouseup(function () {
						if (g.multisel) {
							g.multisel = false;
							$(g.gDiv).noSelect(false);
						}
					}).hover(function (e) {
						if (g.multisel) {
							$(this).toggleClass('trSelected');
						}
					}, function () {}).dblclick(function(){
						p.selectId = $(this).attr("id").substr(3);
						if(p.onselect){
							p.onselect.call("select",g.gDiv,$(t),p,p.onselect.params);
						}
						p.selectId=false;
						//this.onpress(this.name, g.gDiv,$(t),p,this.params);
					});
					if ($.browser.msie && $.browser.version < 7.0) {
						$(this).hover(function () {
							$(this).addClass('trOver');
						}, function () {
							$(this).removeClass('trOver');
						});
					}
				});
			},
			//清空自定义的查询条件缓存
			clearDefCache: function() {
				//如果需要进行查询后的缓存处理，点击查询按钮时，清空所有缓存条件的值
				if(p.cacheDefProps && p.cacheDefProps.length > 0) {
					//根据是否需要显示sDiv，来控制显示的是sDiv还是searchDiv
					var targetSearchDiv = p.showSdiv ? g.sDiv : p.searchDiv;
					$.each(p.cacheDefProps, function(i, cacheDefProp){
						var eleId = cacheDefProp.id; //缓存隐藏域的id
						var targetEle = $(eleId, targetSearchDiv);
						//如果根据id能找到对应的缓存隐藏域，将缓存值清空
						if(targetEle.length > 0) {
							targetEle.val("");
						}
					});
				}
			},
			pager: 0
		};
		//TODO 获取cookie设置
		g.cookieSet();
		if (p.colModel) { //create model if any
			thead = document.createElement('thead');
			var tr = document.createElement('tr');
			//TODO 添加复选框处理
			if(p.showchecked){
				var th = document.createElement('th');
				//如果没有配置复选框的点击事件，才显示全选复选框
				if(p.checkAll) {
					th.innerHTML = '<input type="checkbox" class="cbxAll" onclick="checkAll(this)"/>';
				}
				$(th).attr('width', 30);
				$(tr).append(th);
			}
			for (var i = 0; i < p.colModel.length; i++) {
				var cm = p.colModel[i];
				var th = document.createElement('th');
				//alert(cm.display);
				th.innerHTML = cm.display;
				//alert(cm.sortable);
				
				$(th).attr('colWidth', cm.width);
				$(th).attr('ckabbr', cm.name);
				if(cm.sortable){
					$(th).attr('abbr', cm.name);
					//排序修改
					if(cm.sortName){
						$(th).attr('abbr', cm.sortName);
					}
					
				}
				
				$(th).attr('axis', 'col' + i);
				if (cm.align) {
					th.align = cm.align;
				}
				if (cm.width) {
					//alert(cm.width);
					$(th).attr('width', cm.width);
				}
				if ($(cm).attr('hide')) {
					th.hidden = true;
				}
				if (cm.process) {
					th.process = cm.process;
				}
				$(tr).append(th);
			}
			$(thead).append(tr);
			$(t).prepend(thead);
		} // end if p.colmodel
		//init divs
		g.gDiv = document.createElement('div'); //create global container
		g.mDiv = document.createElement('div'); //create title container
		g.hDiv = document.createElement('div'); //create header container
		g.bDiv = document.createElement('div'); //create body container
		g.vDiv = document.createElement('div'); //create grip
		g.rDiv = document.createElement('div'); //create horizontal resizer
		g.cDrag = document.createElement('div'); //create column drag
		g.block = document.createElement('div'); //creat blocker
		g.nDiv = document.createElement('div'); //create column show/hide popup
		g.nBtn = document.createElement('div'); //create column show/hide button
		g.iDiv = document.createElement('div'); //create editable layer
		g.tDiv = document.createElement('div'); //create toolbar
		g.sDiv = document.createElement('div');//create search container
		g.pDiv = document.createElement('div'); //create pager container
		$(window.top).resize(function(){
			//alert(4);
			//return false;
			//g.setbdivheight();
		});
		//不显示分页工具栏
		if (!p.usepager) {
			g.pDiv.style.display = 'none';
		}
		//不显示功能按钮工具栏
		if(!p.useBtn) {
			g.tDiv.style.display = 'none';
		}
		//不显示搜索层
		if(!p.useSearch) {
			g.sDiv.style.display = 'none';
		}
		g.hTable = document.createElement('table');
		g.gDiv.className = 'flexigrid';
		if (p.width != 'auto') {
			g.gDiv.style.width = p.width + 'px';
		}
		//add conditional classes
		if ($.browser.msie) {
			$(g.gDiv).addClass('ie');
		}
		if (p.novstripe) {
			$(g.gDiv).addClass('novstripe');
		}
		$(t).before(g.gDiv);
		$(g.gDiv).append(t);
		//set toolbar
		if (p.buttons) {
			g.tDiv.className = 'tDiv';
			var tDiv2 = document.createElement('div');
			tDiv2.className = 'tDiv2';
			for (var i = 0; i < p.buttons.length; i++) {
				var btn = p.buttons[i];
				if (!btn.separator) {
					var btnDiv = document.createElement('div');
					btnDiv.className = 'fbutton';
					btnDiv.innerHTML = "<div><span>" + btn.name + "</span></div>";
					if (btn.bclass) $('span', btnDiv).addClass(btn.bclass).css({
						paddingLeft: 20
					});
					btnDiv.onpress = btn.onpress;
					btnDiv.name = btn.name;
					// btn.params 点击事件附加参数
					btnDiv.params = btn.params;
					if (btn.onpress) {
						$(btnDiv).click(function () {
							// btn.params 点击事件附加参数
							this.onpress(this.name, g.gDiv,$(t),p,this.params);
						});
					}
					$(tDiv2).append(btnDiv);
					if ($.browser.msie && $.browser.version < 7.0) {
						$(btnDiv).hover(function () {
							$(this).addClass('fbOver');
						}, function () {
							$(this).removeClass('fbOver');
						});
					}
				} else {
					$(tDiv2).append("<div class='btnseparator'></div>");
				}
			}
			$(g.tDiv).append(tDiv2);
			$(g.tDiv).append("<div style='clear:both'></div>");
			$(g.gDiv).prepend(g.tDiv);
		}
		g.hDiv.className = 'hDiv';
		$(t).before(g.hDiv);
		g.hTable.cellPadding = 0;
		g.hTable.cellSpacing = 0;
		$(g.hDiv).append('<div class="hDivBox"></div>');
		$('div', g.hDiv).append(g.hTable);
		var thead = $("thead:first", t).get(0);
		if (thead) $(g.hTable).append(thead);
		thead = null;
		if (!p.colmodel) var ci = 0;
		//表头事件绑定
		$('thead tr:first th', g.hDiv).each(function () {
			var thdiv = document.createElement('div');
			if ($(this).attr('abbr')) {
				$(this).click(function (e) {
					if (!$(this).hasClass('thOver')) return false;
					var obj = (e.target || e.srcElement);
					if (obj.href || obj.type) return true;
					g.changeSort(this);
				});
				/*if ($(this).attr('abbr') == p.sortname) {
					this.className = 'sorted';
					thdiv.className = 's' + p.sortorder;
				}*/
				//如果有设置排序属性和排序规则，进行排序样式设置
				if(p.sortname && p.sortorder) {
					var sortnames = p.sortname.split(","); //排序属性集
					var sortorders = p.sortorder.split(","); //排序规则集
					var currPropName = $(this).attr('abbr'); //获取当前属性
					var sortIndex = $.inArray(currPropName, sortnames);
					//如果当前属性在排序属性集中，设置排序规则
					if(sortIndex !== -1) {
						$(this).prop("class", "sorted");
						$(thdiv).prop("class", "s" + sortorders[sortIndex]);
					}
				}
			}
			if (this.hidden) {
				$(this).hide();
			}
			if (!p.colmodel) {
				$(this).attr('axis', 'col' + ci++);
			}
			$(thdiv).css({
				textAlign: this.align,
				width: this.width + 'px'
			});
			thdiv.innerHTML = this.innerHTML;
			$(this).empty().append(thdiv).removeAttr('width').mousedown(function (e) {
				g.dragStart('colMove', e, this);
			}).hover(function () {
				if (!g.colresize && !$(this).hasClass('thMove') && !g.colCopy) {
					$(this).addClass('thOver');
				}
				/*if ($(this).attr('abbr') != p.sortname && !g.colCopy && !g.colresize && $(this).attr('abbr')) {
					$('div', this).addClass('s' + p.sortorder);
				} else if ($(this).attr('abbr') == p.sortname && !g.colCopy && !g.colresize && $(this).attr('abbr')) {
					var no = (p.sortorder == 'asc') ? 'desc' : 'asc';
					$('div', this).removeClass('s' + p.sortorder).addClass('s' + no);
				}*/
				//设置了排序属性和排序规则的情况
				if(p.sortname && p.sortorder) {
					var sortnames = p.sortname.split(","); //排序属性集
					var sortorders = p.sortorder.split(","); //排序规则集
					var currPropName = $(this).attr('abbr'); //获取当前属性
					var sortIndex = $.inArray(currPropName, sortnames);
					if(currPropName && !g.colCopy && !g.colresize) {
						//如果当前属性在排序属性集中，反向设置排序规则
						if (sortIndex !== -1) {
							var currPropOrder = sortorders[sortIndex];
							var no = (currPropOrder == 'asc') ? 'desc' : 'asc';
							$('div', this).removeClass('s' + currPropOrder).addClass('s' + no);
						} else {
						//如果当前属性不在排序属性集中，设置为排序属性集中第一个元素的排序规则
							$('div', this).addClass('s' + sortorders[0]);
						}
					}
				}
				
				if (g.colCopy) {
					var n = $('th', g.hDiv).index(this);
					if (n == g.dcoln) {
						return false;
					}
					if (n < g.dcoln) {
						$(this).append(g.cdropleft);
					} else {
						$(this).append(g.cdropright);
					}
					g.dcolt = n;
				} else if (!g.colresize) {
					var nv = $('th:visible', g.hDiv).index(this);
					var onl = parseInt($('div:eq(' + nv + ')', g.cDrag).css('left'));
					var nw = jQuery(g.nBtn).outerWidth();
					var nl = onl - nw + Math.floor(p.cgwidth / 2);
					$(g.nDiv).hide();
					$(g.nBtn).hide();
					//TODO 复选框不显示选择列对象
					if(p.showHideCol){
						if(!p.showchecked||$(this).attr('axis')!='col0'){
							$(g.nBtn).css({
								'left': nl,
								top: g.hDiv.offsetTop
							}).show();
						}
					}
					var ndw = parseInt($(g.nDiv).width());
					$(g.nDiv).css({
						top: g.bDiv.offsetTop
					});
					if ((nl + ndw) > $(g.gDiv).width()) {
						$(g.nDiv).css('left', onl - ndw + 1);
					} else {
						$(g.nDiv).css('left', nl);
					}
					if ($(this).hasClass('sorted')) {
						$(g.nBtn).addClass('srtd');
					} else {
						$(g.nBtn).removeClass('srtd');
					}
				}
			}, function () {
				$(this).removeClass('thOver');
				
				/*if ($(this).attr('abbr') != p.sortname) {
					$('div', this).removeClass('s' + p.sortorder);
				} else if ($(this).attr('abbr') == p.sortname) {
					var no = (p.sortorder == 'asc') ? 'desc' : 'asc';
					$('div', this).addClass('s' + p.sortorder).removeClass('s' + no);
				}*/
				
				//设置了排序属性和排序规则的情况
				if(p.sortname && p.sortorder) {
					var sortnames = p.sortname.split(","); //排序属性集
					var sortorders = p.sortorder.split(","); //排序规则集
					var currPropName = $(this).attr('abbr'); //获取当前属性
					var sortIndex = $.inArray(currPropName, sortnames);
					if(currPropName) {
						//如果当前属性在排序属性集中，反向设置排序规则
						if (sortIndex !== -1) {
							var currPropOrder = sortorders[sortIndex];
							var no = (currPropOrder == 'asc') ? 'desc' : 'asc';
							$('div', this).addClass('s' + currPropOrder).removeClass('s' + no);
						} else {
						//如果当前属性不在排序属性集中，移除排序属性集中第一个元素的样式（由于之前mouseover的时候，设置的也是第一个）
							$('div', this).removeClass('s' + sortorders[0]);
						}
					}
				}
				
				if (g.colCopy) {
					$(g.cdropleft).remove();
					$(g.cdropright).remove();
					g.dcolt = null;
				}
			}); //wrap content
		});
		
		// add title
		if (p.title) {
			g.mDiv.className = 'mDiv';
			g.mDiv.innerHTML = '<div class="ftitle">' + p.title + '</div>';
			$(g.gDiv).prepend(g.mDiv);
			if (p.showTableToggleBtn) {
				$(g.mDiv).append('<div class="ptogtitle" title="Minimize/Maximize Table"><span></span></div>');
				$('div.ptogtitle', g.mDiv).click(function () {
					$(g.gDiv).toggleClass('hideBody');
					$(this).toggleClass('vsble');
				});
			}
		}
		
		// add pager
		$(t).before(g.pDiv);
		if (p.usepager) {
			g.pDiv.className = 'pDiv';
			g.pDiv.innerHTML = '<div class="pDiv2"></div>';
			//$(t).before(g.pDiv);
			//$(g.bDiv).after(g.pDiv);
			var html = ' <div class="pGroup"> <div class="pFirst pButton"><span></span></div><div class="pPrev pButton"><span></span></div> </div> <div class="btnseparator"></div> <div class="pGroup"><span class="pcontrol">' + p.pagetext + ' <input type="text" size="4" value="1" style="height:20px"/> ' + p.outof + ' <span> 1 </span></span></div> <div class="btnseparator"></div> <div class="pGroup"> <div class="pNext pButton"><span></span></div><div class="pLast pButton"><span></span></div> </div> <div class="btnseparator"></div> <div class="pGroup"> <div class="pReload pButton"><span></span></div> </div> <div class="btnseparator"></div> <div class="pGroup"><span class="pPageStat"></span></div><div class="pGroup"><span class="pPageStat executeTime"></span></div>';
			$('div', g.pDiv).html(html);
			$('.pReload', g.pDiv).click(function () {
				//清空自定义的查询条件缓存
				g.clearDefCache();
				g.populate();
			});
			$('.pFirst', g.pDiv).click(function () {
				g.changePage('first');
			});
			$('.pPrev', g.pDiv).click(function () {
				g.changePage('prev');
			});
			$('.pNext', g.pDiv).click(function () {
				g.changePage('next');
			});
			$('.pLast', g.pDiv).click(function () {
				g.changePage('last');
			});
			$('.pcontrol input', g.pDiv).keydown(function (e) {
				if (e.keyCode == 13) g.changePage('input');
			});
			if ($.browser.msie && $.browser.version < 7) $('.pButton', g.pDiv).hover(function () {
				$(this).addClass('pBtnOver');
			}, function () {
				$(this).removeClass('pBtnOver');
			});
			//TODO 去除下拉选项
			if (p.useRp) {
				var opt = '',
					sel = '';
				for (var nx = 0; nx < p.rpOptions.length; nx++) {
					if (p.rp == p.rpOptions[nx]) sel = 'selected="selected"';
					else sel = '';
					opt += "<option value='" + p.rpOptions[nx] + "' " + sel + " >" + p.rpOptions[nx] + "&nbsp;&nbsp;</option>";
				}
				$('.pDiv2', g.pDiv).prepend("<div class='pGroup'><select name='rp' style='height:20px'>" + opt + "</select></div> <div class='btnseparator'></div>");
				$('select', g.pDiv).change(function () {
					if (p.onRpChange) {
						p.onRpChange(+this.value);
					} else {
						p.newp = 1;
						p.rp = +this.value;
						g.populate();
					}
				});
			}
			
		}
		//add search button
		if (p.searchitems) {
			//add search box
			g.sDiv.className = 'sDiv';
			//根据是否需要显示sDiv，来控制显示的是sDiv还是searchDiv
			var targetSearchDiv = p.showSdiv ? g.sDiv : p.searchDiv;
			//TODO 查询修改
			if(p.searchDiv!=''){
				$(g.sDiv).empty();
				$(g.sDiv).append($(p.searchDiv).html());
				$(':button[value="搜索"]',g.sDiv).click(function(){
					g.doSearch();
				});
				//alert($(':button',g.sDiv).filter('.searchbtn').size());
				//需要显示sDiv的情况，隐藏searchDiv
				if(p.showSdiv) {
					//使用搜索层时，才显示sDiv
					if(p.useSearch) {
						$(g.sDiv).show();
					}
					$(p.searchDiv).hide();
				} else {
				//不需要显示sDiv的情况，设置sDiv的高度后进行隐藏(用于计算flexgrid的高度时使用)，显示searchDiv
					var sDivSrcHeight = $(g.sDiv).height();
					$(g.sDiv).height(sDivSrcHeight).hide();
					$(p.searchDiv).show();
				}
				//由于增加了搜索层全部和局部显示功能，导致搜索按钮可能出现动态生成的情况，搜索按钮需通过live绑定点击事件(蒙飞鸿)
				//根据当前显示的是sDiv或者searchDiv进行查询按钮的点击事件绑定
				$('.searchbtn', targetSearchDiv).live("click", function(){
					//清空自定义的查询条件缓存
					g.clearDefCache();
					g.doSearch();
				});
			}		
			//$(g.bDiv).after(g.sDiv);
			if(p.title){
				$(g.mDiv).before(g.sDiv);//修改查询条件显示位置
			}else{
				$(g.tDiv).before(g.sDiv);
			}
			//使用搜索层的情况，才设置搜索层显隐按钮条
			if(p.useSearch) {
				//搜索层显隐按钮条
				var pSearch = $("<div class='pSearch'><div class='frameControlVFlex pSearchtop'></div></div>");
				$(g.sDiv).after(pSearch);
				pSearch.click(function() {
					//根据是否需要显示sDiv，来控制是sDiv还是searchDiv绑定显隐事件
					$(targetSearchDiv).slideToggle('fast', function() {
						var oldht = $(g.bDiv).height();
						//alert('修改前'+oldht);
						var newht = 0;
						if($(this).css("display") === 'none') {
							//newht = oldht + g.serachHeight;
							newht = oldht + $(this).height();
							$('.frameControlVFlex', pSearch).addClass("pSearchbottom");
						} else {
							//newht = oldht - g.serachHeight;
							newht = oldht - $(this).height();
							$('.frameControlVFlex', pSearch).removeClass("pSearchbottom");
						}
						$(g.bDiv).height(newht);
						//$('.sDiv:visible input:first', g.gDiv).trigger('focus');
					});
				});
				//不需要显示sDiv的情况，隐藏搜索层显隐按钮条
				if(!p.showSdiv) {
					pSearch.hide();
				}
			}
		}
		$(g.pDiv, g.sDiv).append("<div style='clear:both'></div>");
		
		//set bDiv
		g.bDiv.className = 'bDiv';
		//$(t).before(g.bDiv);
		$(g.pDiv).before(g.bDiv);
//		if(p.height!=='auto'){
//			g.setbdivheight().scroll(function (e) {
//				g.scroll();
//			}).append(t);
//		}
		g.setbdivheight().scroll(function (e) {
			g.scroll();
		}).append(t);
		if (p.height == 'auto') {
			//$('table', g.bDiv).addClass('autoht');
		}
		//add td & row properties
		g.addCellProp();
		g.addRowProp();
		//set cDrag
		var cdcol = $('thead tr:first th:first', g.hDiv).get(0);
		if (cdcol != null) {
			g.cDrag.className = 'cDrag';
			g.cdpad = 0;
			g.cdpad += (isNaN(parseInt($('div', cdcol).css('borderLeftWidth'))) ? 0 : parseInt($('div', cdcol).css('borderLeftWidth')));
			g.cdpad += (isNaN(parseInt($('div', cdcol).css('borderRightWidth'))) ? 0 : parseInt($('div', cdcol).css('borderRightWidth')));
			g.cdpad += (isNaN(parseInt($('div', cdcol).css('paddingLeft'))) ? 0 : parseInt($('div', cdcol).css('paddingLeft')));
			g.cdpad += (isNaN(parseInt($('div', cdcol).css('paddingRight'))) ? 0 : parseInt($('div', cdcol).css('paddingRight')));
			g.cdpad += (isNaN(parseInt($(cdcol).css('borderLeftWidth'))) ? 0 : parseInt($(cdcol).css('borderLeftWidth')));
			g.cdpad += (isNaN(parseInt($(cdcol).css('borderRightWidth'))) ? 0 : parseInt($(cdcol).css('borderRightWidth')));
			g.cdpad += (isNaN(parseInt($(cdcol).css('paddingLeft'))) ? 0 : parseInt($(cdcol).css('paddingLeft')));
			g.cdpad += (isNaN(parseInt($(cdcol).css('paddingRight'))) ? 0 : parseInt($(cdcol).css('paddingRight')));
			$(g.bDiv).before(g.cDrag);
			var cdheight = $(g.bDiv).height();
			var hdheight = $(g.hDiv).height();
			$(g.cDrag).css({
				top: -hdheight + 'px'
			});
			$('thead tr:first th', g.hDiv).each(function () {
				var cgDiv = document.createElement('div');
				$(g.cDrag).append(cgDiv);
				if (!p.cgwidth) {
					p.cgwidth = $(cgDiv).width();
				}
				$(cgDiv).css({
					height: cdheight + hdheight
				}).mousedown(function (e) {
					g.dragStart('colresize', e, this);
				});
				if ($.browser.msie && $.browser.version < 7.0) {
					g.fixHeight($(g.gDiv).height());
					$(cgDiv).hover(function () {
						g.fixHeight();
						$(this).addClass('dragging');
					}, function () {
						if (!g.colresize) $(this).removeClass('dragging');
					});
				}
			});
		}
		//add strip
		if (p.striped) {
			$('tbody tr:odd', g.bDiv).addClass('erow');
		}
		if (p.resizable && p.height != 'auto') {
			g.vDiv.className = 'vGrip';
			$(g.vDiv).mousedown(function (e) {
				g.dragStart('vresize', e);
			}).html('<span></span>');
			$(g.bDiv).after(g.vDiv);
		}
		if (p.resizable && p.width != 'auto' && !p.nohresize) {
			g.rDiv.className = 'hGrip';
			$(g.rDiv).mousedown(function (e) {
				g.dragStart('vresize', e, true);
			}).html('<span></span>').css('height', $(g.gDiv).height());
			if ($.browser.msie && $.browser.version < 7.0) {
				$(g.rDiv).hover(function () {
					$(this).addClass('hgOver');
				}, function () {
					$(this).removeClass('hgOver');
				});
			}
			$(g.gDiv).append(g.rDiv);
		}		
		
		
		//setup cdrops
		g.cdropleft = document.createElement('span');
		g.cdropleft.className = 'cdropleft';
		g.cdropright = document.createElement('span');
		g.cdropright.className = 'cdropright';
		//add block
		g.block.className = 'gBlock';
		var gh = $(g.bDiv).height();
		var gtop = g.bDiv.offsetTop;
		$(g.block).css({
			width: g.bDiv.style.width,
			height: gh,
			background: 'white',
			position: 'relative',
			marginBottom: (gh * -1),
			zIndex: 1,
			top: gtop,
			left: '0px'
		});
		$(g.block).fadeTo(0, p.blockOpacity);
		// add column control
		if ($('th', g.hDiv).length) {
			g.nDiv.className = 'nDiv';
			g.nDiv.innerHTML = "<table cellpadding='0' cellspacing='0'><tbody></tbody></table>";
			$(g.nDiv).css({
				marginBottom: (gh * -1),
				display: 'none',
				top: gtop
			}).noSelect();
			//为nDiv添加name,赋值为p.cookieId
			$(g.nDiv).attr('name',p.cookieId);
			var cn = 0;
			$('th div', g.hDiv).each(function () {
				//TODO 去除复选框隐藏
				if(p.showchecked&&cn==0){cn++;return;}
				var kcol = $("th[axis='col" + cn + "']", g.hDiv)[0];
				//TODO 获取该列的属性名
				var attrName = $(kcol).attr('ckabbr');
				var attrCookieName = p.cookieId+'.'+attrName;
				var attrChk = $.cookie(attrCookieName);
				var colWidth = $(kcol).attr('colWidth');
				if(!colWidth) {
					colWidth = '';
				}
				var chk = 'checked="'+attrChk+'"';
				if (kcol.style.display == 'none') {
					chk = '';
				}
				$('tbody', g.nDiv).append('<tr><td class="ndcol1"><input name="' + attrCookieName + '" colWidth="'+colWidth+'" type="checkbox" ' + chk + ' class="togCol" value="' + cn + '" /></td><td class="ndcol2">' + this.innerHTML + '</td></tr>');
				cn++;
			});
			if ($.browser.msie && $.browser.version < 7.0) $('tr', g.nDiv).hover(function () {
				$(this).addClass('ndcolover');
			}, function () {
				$(this).removeClass('ndcolover');
			});
			$('td.ndcol2', g.nDiv).click(function () {
				if ($('input:checked', g.nDiv).length <= p.minColToggle && $(this).prev().find('input')[0].checked) return false;
				return g.toggleCol($(this).prev().find('input').val());
			});
			$('input.togCol', g.nDiv).click(function () {
				if ($('input:checked', g.nDiv).length < p.minColToggle && this.checked == false) return false;
				$(this).parent().next().trigger('click');
			});
			$(g.gDiv).prepend(g.nDiv);
			$(g.nBtn).addClass('nBtn')
				.html('<div></div>')
				.attr('title', 'Hide/Show Columns')
				.click(function () {
					$(g.nDiv).toggle();
					return true;
				}
			);
			if (p.showToggleBtn) {
				$(g.gDiv).prepend(g.nBtn);
			}
		}
		// add date edit layer
		$(g.iDiv).addClass('iDiv').css({
			display: 'none'
		});
		$(g.bDiv).append(g.iDiv);
		// add flexigrid events
		$(g.bDiv).hover(function () {
			$(g.nDiv).hide();
			$(g.nBtn).hide();
		}, function () {
			if (g.multisel) {
				g.multisel = false;
			}
		});
		$(g.gDiv).hover(function () {}, function () {
			$(g.nDiv).hide();
			$(g.nBtn).hide();
		});
		//add document events
		$(document).mousemove(function (e) {
			g.dragMove(e);
		}).mouseup(function (e) {
			g.dragEnd();
		}).hover(function () {}, function () {
			g.dragEnd();
		});
		//browser adjustments
		if ($.browser.msie && $.browser.version < 7.0) {
			$('.hDiv,.bDiv,.mDiv,.pDiv,.vGrip,.tDiv, .sDiv', g.gDiv).css({
				width: '100%'
			});
			$(g.gDiv).addClass('ie6');
			if (p.width != 'auto') {
				$(g.gDiv).addClass('ie6fullwidthbug');
			}
		}
		g.rePosDrag();
		g.fixHeight();
		//make grid functions accessible
		t.p = p;
		t.grid = g;
		
		// load data
		if (p.url && p.autoload) {
			g.populate();
		}
		return t;
	};
	var docloaded = false;
	$(document).ready(function () {
		docloaded = true;
	});
	$.fn.flexigrid = function (p) {
		return this.each(function () {
			if (!docloaded) {
				$(this).hide();
				var t = this;
				$(document).ready(function () {
					$.addFlex(t, p);
				});
			} else {
				$.addFlex(this, p);
			}
		});
	}; //end flexigrid
	$.fn.flexReload = function (p) { // function to reload grid
		return this.each(function () {
			if (this.grid && this.p.url) this.grid.populate();
			else{
				if (!docloaded) {
					$(this).hide();
					var t = this;
					$(document).ready(function () {
						$.addFlex(t, p);
					});
				} else {
					$.addFlex(this, p);
				}
			}
		});
	}; //end flexReload
	$.fn.flexOptions = function (p) { //function to update general options
		return this.each(function () {
			if (this.grid) $.extend(this.p, p);
		});
	}; //end flexOptions
	$.fn.flexToggleCol = function (cid, visible) { // function to reload grid
		return this.each(function () {
			if (this.grid) this.grid.toggleCol(cid, visible);
		});
	}; //end flexToggleCol
	$.fn.flexAddData = function (data) { // function to add data to grid
		return this.each(function () {
			if (this.grid) this.grid.addData(data);
		});
	};
	$.fn.noSelect = function (p) { //no select plugin by me :-)
		var prevent = (p == null) ? true : p;
		if (prevent) {
			return this.each(function () {
				if ($.browser.msie || $.browser.safari) $(this).bind('selectstart', function () {
					return false;
				});
				else if ($.browser.mozilla) {
					$(this).css('MozUserSelect', 'none');
					$('body').trigger('focus');
				} else if ($.browser.opera) $(this).bind('mousedown', function () {
					return false;
				});
				else $(this).attr('unselectable', 'on');
			});
		} else {
			return this.each(function () {
				if ($.browser.msie || $.browser.safari) $(this).unbind('selectstart');
				else if ($.browser.mozilla) $(this).css('MozUserSelect', 'inherit');
				else if ($.browser.opera) $(this).unbind('mousedown');
				else $(this).removeAttr('unselectable', 'on');
			});
		}
	}; //end noSelect
})(jQuery);